<template>
	<view class="content">
		<view class="search_box">
			<!-- 搜索 -->
			<view class="search-form">
				<view class="title-item" @tap="showAddressPop">
					<view class="title">{{ city }}</view>
					<u-image width="14rpx" height="7rpx" :src="getServerStatic('/static/images/a39.png')" ></u-image>
				</view>
				<u-search placeholder="请输入预约门店" v-model="keyword" :showAction="false" @search="handleSearch" @focus="searchStores = []"></u-search>
			</view>
			<!-- 当前定位 -->
			<view class="now-position" v-if="!keyword">
				<view class="position">{{ currentLocation }}</view>
				<view class="refresh-box" @click="handleLocation">
					<u-icon name="map-fill" color="#333333" size="20"></u-icon>
					<view class="">重新定位</view>
				</view>
			</view>
		</view>
		<view class="search_result" v-if="keyword">
			<view class="search_title">搜索结果</view>
			<view class="result_list">
				<view class="result_box" v-for="(item,index) in searchStores" :key="index">
					<view class="shop_name">{{ item.name }}</view>
					<view class="shop_address">{{ item.address }}</view>
				</view>
			</view>
		</view>


        <!-- 地址三级联动 -->
        <!-- 省市区选择 province city area初始省市区设置 show:是否显示  @changeClick：更改省市区事件 @sureSelectArea：确认事件 @hideShow：隐藏事件-->
        <view v-if="showComponent">
            <cc-selectDity :province="province" :city="city" :area="area" :show="addressPop" :showArea="false" @changeClick="changeClick" @sureSelectArea="confirmArea" @hideShow="addressPop = false"></cc-selectDity>
        </view>

		<template>
			<view class="search_result" v-if="userStore.token">
				<view class="search_title">常用门店</view>
				<view class="result_list">
					<view class="result_box" v-for="(item, index) in commonUseStores" :key="index" @click="handleChoseStore(item.hospital_id)">
						<view class="shop_name">{{ item.name }}</view>
						<view class="shop_address">{{ item.address }}</view>
					</view>
				</view>
			</view>

			<view class="search_result" v-show="nearbyStores.length > 0">
				<view class="search_title">附近门店</view>
				<view class="result_list">
					<view class="result_box" v-for="(item, index) in nearbyStores" :key="index" @click="handleChoseStore(item.id)">
						<view class="shop_name">{{ item.name }}</view>
						<view class="shop_address">{{ item.address }}</view>
					</view>
				</view>
			</view>

		</template>

        <u-modal showCancelButton :show="useStorePop" title="切换门店" @cancel="useStorePop = false" @confirm="confirmUseStore" confirmColor="#3165DF">
            <view class="confirm-tip">是否确定切换门店 ？</view>
        </u-modal>

	</view>
</template>

<script setup>
    import {ref, reactive, readonly} from "vue"
    import {onLoad, onShow} from '@dcloudio/uni-app'
    import QQMapWX from "@/utils/qqmap-wx-jssdk.js"
    import {Config} from "@/common/config";
    import { useHospitalStore, useUserStore } from '@/store';
    import {getCache, setCache} from "@/utils/cache";
    import {
        getCommonUseStores,
        getHospitalsByCity,
        getHospitalsByPosition,
        getHospitalsBySearchKeyword
    } from "@/api/hospital";
    import useUniAPi from "@/hooks/useUniAPi";
    import {getServerStatic} from "@/utils/tool";
    const { navigateTo, redirectTo } = useUniAPi()

    // 医院store
    const hospitalStore = useHospitalStore()
    // 用户store
    const userStore = useUserStore();

    const useStorePop = ref(false)

	const keyword = ref('')
    const showComponent = ref(true)
    // 展示弹窗
    const addressPop = ref(false)

    // 默认的城市 使用默认门店的位置
    const province = ref(hospitalStore.province)
    const city = ref(hospitalStore.city)
    const area = ref(hospitalStore.district)

    // 当前位置
    const currentLocation = ref('...')
    const currentLatitude = ref(null)
    const currentLongitude = ref(null)

    // 附近门店
    const nearbyStores = ref([])

    // 常用门店
    const commonUseStores = ref([])

    // 搜索门店
    const searchStores = ref([])

    const tMap = new QQMapWX({
        key: Config.MAP_KEY //开发者密钥
    });

    onLoad(() => {
        // 获取缓存位置信息.
        handleGetCacheLocation()

        // 获取附近门店
        handleGetNearStoresByLocation()

        handleGetCommonUseStores()
    })

    // 获取缓存的位置信息
    const handleGetCacheLocation = () => {
        let cacheCurrentLocation = getCache('currentLocation')
        let latitude = getCache('latitude');
        let longitude = getCache('longitude');
        console.log('缓存的位置', currentLocation)
        console.log('纬度', latitude)
        console.log('经度', longitude)
        if (!cacheCurrentLocation || cacheCurrentLocation.length <= 0) {
            currentLocation.value = '当前: 请重新授权获取'
        } else {
            currentLocation.value = "当前: " + cacheCurrentLocation
            currentLatitude.value = latitude
            currentLongitude.value = longitude
        }
    }

    // 附近的门店
    const handleGetNearStoresByLocation = async () => {
        if (currentLatitude.value && currentLongitude.value) {
            console.log('获取附近门店的纬度', currentLocation.value)
            console.log('获取附近门店的经度', currentLongitude.value)
            const {code, data} = await getHospitalsByPosition({
                lat: currentLatitude.value,
                lng: currentLongitude.value,
                store_id: hospitalStore.id
            })

            if (code == 1) {
                console.log('附近的门店', data)
                nearbyStores.value = data
            }

        }
    }

    const handleGetCommonUseStores = async () => {
        if (userStore.token) {
            const {code, data} = await getCommonUseStores({})
            if (code == 1) {
                commonUseStores.value = data
            }
        }
    }

    // 申请位置权限
    const handleLocation = () => {
        uni.getSetting({
            success(res) {
                console.log(res)
                if (!res.authSetting['scope.userLocation']) {
                    uni.authorize({
                        scope: 'scope.userLocation',
                        success() { //1.1 允许授权
                            console.log('同意授权')
                            handleGetLocation()
                        },
                        fail(error) {
                            console.log('拒绝授权', error)
                            uni.showModal({
                                title: '提示',
                                content: '若点击不授权，将无法使用位置功能',
                                cancelText: '不授权',
                                cancelColor: '#999',
                                confirmText: '授权',
                                confirmColor: '#f94218',
                                success (res) {
                                    console.log(res)
                                    if (res.confirm) {
                                        // 选择弹框内授权
                                        uni.openSetting({
                                            success (res) {
                                                console.log(res.authSetting)
                                            }
                                        })
                                    } else if (res.cancel) {
                                        // 选择弹框内 不授权
                                        console.log('用户点击不授权')
                                    }
                                }
                            })
                        }
                    })
                } else {
                    handleGetLocation()
                }
            }
        });

    }

    // 逆地址解析
    const handleGetLocation = () => {
        uni.getLocation({
            type: 'wgs84',
            geocode: true,
            success: (res) => {
                console.log("纬度经度", res.latitude, res.longitude)
                let latitude = res?.latitude // 纬度
                let longitude = res?.longitude // 经度
                currentLatitude.value = latitude
                currentLongitude.value = longitude
                // 使用腾讯sdk的reverseGeocoder方法 解析经纬度
                tMap.reverseGeocoder({
                    location: {
                        latitude: latitude,
                        longitude:longitude
                    },
                    success: function(res) {
                        console.log("解析地址成功", res);
                        console.log("当前地址：", res.result.address);

                        province.value = res.result.ad_info.province
                        city.value = res.result.ad_info.city
                        area.value = res.result.ad_info.district
                        currentLocation.value = "当前: " + res.result.address
                        //保存缓存
                        setCache('latitude', latitude);
                        setCache('longitude', longitude);
                        setCache('currentLocation', res.result.address);
                        console.log("用户地址信息已缓存")

                        handleGetNearStoresByLocation()
                    },
                    fail: function(res) {
                        uni.showToast({
                            title: '定位失败',
                            duration: 2000,
                            icon: "none"
                        })
                        console.log(res);
                    },
                    complete: function(res) { //无论成功失败都会执行
                        console.log('获取定位信息')
                        return
                    }
                })
            },
            fail: (err) => {
                console.log(err)
            }
        })
    }

    // 展示地址下拉
    const showAddressPop = () => {
        addressPop.value = true
    }

    // 获取省市区
    const changeClick = (province, city, area) => {
        selectProvince.value = province
        selectCity.value = city
        selectArea.value = area
    }

    // 地址选择
    const selectProvince = ref(null)
    const selectCity = ref(null)
    const selectArea = ref(null)

    // 确认
    const confirmArea = (e) => {
        addressPop.value = false

        province.value = selectProvince.value ?? province.value
        city.value = selectCity.value ?? city.value
        area.value = selectArea.value ?? area.value

        console.log('切换的地区', city.value)

        handleGetNearStoresByCity()
    }

    // 获取门店通过城市
    const handleGetNearStoresByCity = async () => {
        const {code, data} = await getHospitalsByCity({city: city.value, store_id: hospitalStore.id})
        if (code == 1) {
            console.log('城市名称搜索附近的门店', data)
            nearbyStores.value = data
        }
    }

    // 搜索门店
    const handleSearch = async () => {
        console.log('搜索', keyword.value)
        uni.showLoading({
            title: '搜索中'
        });
        const {code, data} = await getHospitalsBySearchKeyword({city: city.value, keyword: keyword.value })
        uni.hideLoading();
        if (code == 1) {
            console.log('城市名称搜索附近的门店', data)
            searchStores.value = data
        }
    }

    const useStoreId = ref(null)
    // 切换门店
    const handleChoseStore = (storeId) => {
        console.log('切换门店', storeId)
        useStoreId.value = storeId
        useStorePop.value = true
    }

    const confirmUseStore = async () => {
        if (useStoreId.value) {
            await hospitalStore.handleChoseStore(useStoreId.value)
            console.log('切换完成')
            // 返回首页
            // 跳转并销毁当前页
            redirectTo({
                url: "/pages/index/index"
            })
        }
    }
</script>

<style lang="scss" scoped>
	.content {
		background: #F5F6F8;
	}

	.search_box {
		background: #FFFFFF;
		padding: 34rpx 26rpx;
		.search-form {
			@include between(100%);
			.title-item {
				display: flex;
				align-items: center;
				margin-right: 30rpx;
				.title {
					font-size: 28rpx;
					color: #333333;
					margin-right: 10rpx;
				}
			}
		}
		.now-position {
			@include between(100%);
			margin-top: 38rpx;
			font-size: 28rpx;
			color: #333333;
			.refresh-box {
				@include start();
				& > view {
					margin-left: 10rpx;
				}
			}
		}
	}

	.search_result {
		margin-top: 20rpx;
		padding: 30rpx 26rpx;
		background: #FFFFFF;

		.search_title {
			font-size: 32rpx;
			color: #333333;
			font-weight: bold;
			// margin-bottom: 30rpx;
		}

		.result_list {
			// border: 1rpx solid red;
			.result_box {
				padding: 30rpx 26rpx;
				border-bottom: 1rpx solid #E4E4E4;

				.shop_name {

					font-size: 28rpx;
					font-weight: 500;
					color: #333333;
					margin-bottom: 14rpx;
				}

				.shop_address {

					font-size: 26rpx;
					color: #333333;
				}
			}
		}
	}
</style>
